﻿var gaopaiyi=function () {
   var  DemoObj={
       ws:"",
       tryonce:false,
       connected:false,
       server_addr:"ws://127.0.0.1:18888",//本机端口地址
       msg_handler:{},
       orgwidth:0,
       orgheight:0,
       resetx:20,
       resety:20,
       resetwidth:300,
       resetheight:400,
       iswaiting :false,
       context:1,
       callback :{},
       orgdrawwidth:0,
       orgdrawheight: 0,
       capID:0,//默认打开哪个摄像头1身份证2高拍仪
       base64_type1:"",//缓存证件照
       base64_type2:"",//缓存办理人照
       output:function (content) {
                  //打印调试信息函数
           if(content.length ==0){	return;}
           var console = document.getElementById("Console");
           console.value += content;
           console.value += '\r';
           console.scrollTop = console.scrollHeight;

       },
      sendMsg:function (proto, msg, cb) {//向后台发送消息的处理函数
        if(!DemoObj.ws){
          return;
        }

        if(typeof msg !== 'object'){
          if(typeof msg === 'function')
          {
            cb = msg;
            msg = {};
          }
          else{
            msg = {}
          }
        }

        msg.proto = proto;
        if(typeof cb === 'function'){
          DemoObj.context=DemoObj.context+1;
          DemoObj.callback[DemoObj.context] = cb;
          msg.user_data = DemoObj.context;
        }

        DemoObj.ws.send(JSON.stringify(msg));
      }
   };
  // 使用JSON  向服务发送的操作命令
  const CLT_MSG = {
    // 打开相机 cap:相机ID
    BEGIN_CAP : 1,
    // 关闭相机 cap:相机ID
    STOP_CAP : 2,
    // 获取PID
    GET_PID :3,
    // 获取分辨率
    GET_FBL : 4,
    //设置分辨率
    SET_FBL : 5,
    //设置MJPG格式
    SET_MJPG: 6,
    //设置视频旋转
    SET_TURN: 7,
    //设置视频截图保存的jpg质量
    SET_QUALITY:8,
    //设置自动裁边
    SET_AUTOCROP:9,
    //设置预设框选
    SET_PREST:10,
    //获取当前预设框选
    GET_PREST_INFO:11,
    //视频格式弹窗
    FORMAT_DLG:12,
    //视频属性弹窗
    PROPERTY_DLG:13,
    //设置截图颜色模式 彩色 黑白 灰度
    SET_COLOR_MODEL:14,
    //截图
    GET_PICTURE:15,
    //设置去底色参数
    SET_CLEAN_PARAM:16,
    //内存截图
    GET_PICTURE_MEM:17,
    //base64测试
    TEST_BASE64:18,
    //制作PDF的临时目录
    SET_TEMPDIR:19,
    //开始制作PDF
    BEGIN_PDF:20,
    //PDF截图 保存到PDF临时目录
    GET_PDF_PICTURES:21,
    //结束制作PDF
    END_PDF_PICTURES:22,
    //PDF文件转为文件里的BASE64码
    PDF_TO_BASE64:23,
    //文件里的BASE64码转为PDF文件
    BASE64_TO_PDF:24,
    //PDF文件转为BASE64字符串
    PDF_TO_BASE64_STR:25,
    //删除制作PDF的图片文件
    DEL_PICTURE_PDF:26,
    //打印图片
    PRINT_IMAGE:27,
    //设置显示错误弹窗
    SHOW_ERROR_BOX:28,
    //获取视频连接事件
    GET_EVENT:29,
    //预设框选鼠标消息
    PRESET_MOUSEDOWN:30,
    PRESET_MOUSEMOVE:31,
    PRESET_MOUSEUP:32,

    //多图裁剪
    MULTI_DETE:33,
    //人脸检测
    FACE_DETE:34,
    //设置DPI
    SET_DPI:35,
    //版本信息
    LIB_INFO:36,

    //人证对比
    FI_INIT:41,
    IDCARD_COMPARE:40,
    FI_UNIT:42,
  };
  const base_offset = 3;

  const SVR_BIN_MSG = {
    CAP_FRAME : 1, //后台帧消息
  };
  DemoObj.sendMsg=function(proto, msg, cb){ //向后台发送消息的处理函数
    if(!DemoObj.ws){
      return;
    }

    if(typeof msg !== 'object'){
      if(typeof msg === 'function')
      {
        cb = msg;
        msg = {};
      }
      else{
        msg = {}
      }
    }

    msg.proto = proto;
    if(typeof cb === 'function'){
      DemoObj.context=DemoObj.context+1;
      DemoObj.callback[DemoObj.context] = cb;
      msg.user_data = DemoObj.context;
    }

    DemoObj.ws.send(JSON.stringify(msg));
  }
  DemoObj.drawImage=function(data){
      //视频帧绘制函数
      // LE
      // 校验视频是否在一定时间内的
      if(!DemoObj.checkTimestamp(data[2] * 256 + data[1])){
        return;
      }
      //视频帧头有时间戳 注意偏移 和 大小端处理
      var width = data[base_offset + 1] * 256 + data[base_offset];
      var height = data[base_offset + 3] * 256 + data[base_offset + 2];

      var cam = document.getElementById('cam');
      var context = cam.getContext("2d");
      if(DemoObj.orgdrawwidth != width || DemoObj.orgdrawheight != height){
        DemoObj.orgdrawwidth = width;
        DemoObj.orgdrawheight = height
        cam.height = cam.height;
      }

      var image = context.createImageData(width, height);
      for(var n = 0; n != height; ++n){
        for(var m = 0; m != width; ++m)
        {
          var image_offset = ((height - n - 1) * width + m) * 4;
          var data_offset = (n * width + m) * 3 + base_offset + 4;
          image.data[image_offset] 			= data[data_offset + 2];
          image.data[image_offset + 1] 	= data[data_offset + 1];
          image.data[image_offset + 2] 	= data[data_offset];
          image.data[image_offset + 3] 	= 255;
        }
      }
      context.putImageData(image, 0, 0);


  }
  DemoObj.ResetBox=function () {
    //取消预设框选
    if(DemoObj.iswaiting) return;
    DemoObj.iswaiting = true;
    DemoObj.sendMsg(CLT_MSG.SET_PREST, {left:0, top:0, width:0, height:0},function(msg){
      if(msg.err !== 0) {
        DemoObj.iswaiting = false;
        return;
      }
      DemoObj.resetx = 0;
      DemoObj.resety = 0;
      DemoObj.resetwidth = 0;
      DemoObj.resetheight = 0;
      DemoObj.output("取消预设框选");
      DemoObj.iswaiting = false;
    });
  }
  DemoObj.checkTimestamp=function(svr_time)  {
    //检查视频帧时间戳
    var myDate = new Date();
    var clt_time = myDate.getSeconds() * 1000 + myDate.getMilliseconds();
    if(clt_time < svr_time){
      clt_time += 60 * 1000;
    }

    return clt_time - svr_time < 3000;
  }

  return {
    camera:{
        onLoad:function (){//页面load消息
          //判断是否有对象存在，有就返回，没有就继续
          if(DemoObj.ws){
            return;
          }

          //output("正在连接：" + server_addr);
          DemoObj.ws = new WebSocket( DemoObj.server_addr);
          DemoObj.ws.onopen = function(evt)
          {
            if(DemoObj.connected)		{ return;}

            DemoObj.connected = true;
            DemoObj.output("已经连接到服务器");
          };

          DemoObj.ws.onclose = function(evt)
          {
            if(!DemoObj.connected)
            {
              if(!DemoObj.tryonce)
              {
                window.location.href = "FLShell://"
                setTimeout("DemoObj.onLoad()", 1000); //修改此处
                DemoObj.tryonce = true;
              }
              else
              {
                setTimeout("DemoObj.onLoad()", 1000);
              }
            }
            else
            {
              DemoObj.output("已断开服务器连接");
              DemoObj.connected = false;
            }

            DemoObj.ws = null;
          }
          DemoObj.ws.onmessage = function(evt) {
            if(evt.data.length === 0 ){
              return;
            }

            if(typeof evt.data === 'string'){
              var msg = JSON.parse(evt.data);
              if(msg.err && msg.err !== 0){
                DemoObj.output("错误 - " + msg.err + ", " + msg.msg);
              }
              else if(msg.msg){
                DemoObj.output(msg.msg);
              }

              if(msg.user_data){
                DemoObj.callback[msg.user_data](msg);
                if(typeof msg.user_data === 'number'){
                  DemoObj.callback[msg.user_data] = undefined;
                }
              }
            }
            else{
              var file = new FileReader();
              file.onload = function(evt) {
                if(evt.target.readyState == FileReader.DONE){
                  var data = new Uint8Array(evt.target.result);
                  if(data[0] == SVR_BIN_MSG.CAP_FRAME){
                    return   DemoObj.drawImage(data);
                  }
                }
              };

              file.readAsArrayBuffer(evt.data);
            }
          }
          var clicked = false;
          var canvas = document.getElementById("cam");

          canvas.onmousedown = function(e){
            this.style.cursor = "crosshair";

            clicked = true;

            if(e.offsetX && e.offsetY)
              DemoObj.sendMsg(CLT_MSG.PRESET_MOUSEDOWN, {origX:e.offsetX, origY:e.offsetY},function(msg){
                if(msg.err !== 0) { return;}});
            else
              DemoObj.sendMsg(CLT_MSG.PRESET_MOUSEDOWN, {origX:e.layerX, origY:e.layerY},function(msg){
                if(msg.err !== 0) { return;}});
          }

          canvas.onmousemove = function(e){
            if(!clicked) {
              this.style.cursor = "default";
              return;}
            this.style.cursor = "crosshair";

            if(e.offsetX && e.offsetY)
              DemoObj.sendMsg(CLT_MSG.PRESET_MOUSEMOVE, {offx:e.offsetX, offy:e.offsetY},function(msg){
                if(msg.err !== 0) { return;}});
            else
              DemoObj.sendMsg(CLT_MSG.PRESET_MOUSEMOVE, {offx:e.layerX, offy:e.layerY},function(msg){
                if(msg.err !== 0) { return;}});
          }

          canvas.onmouseup = function(e){
            this.style.cursor = "default";
            if(!clicked) {return;}

            if(e.offsetX && e.offsetY)
              DemoObj.sendMsg(CLT_MSG.PRESET_MOUSEUP, {offx:e.offsetX, offy:e.offsetY},function(msg){
                if(msg.err !== 0) { return;}});
            else
              DemoObj.sendMsg(CLT_MSG.PRESET_MOUSEUP, {offx:e.layerX, offy:e.layerY},function(msg){
                if(msg.err !== 0) { return;}});

            clicked = false;
          }
        },output:function (content) {
        if(content.length ==0){	return;}
        var console = document.getElementById("Console");
        console.value += content;
        console.value += '\r';
        console.scrollTop = console.scrollHeight;
      },cam_switch:function (capID) {
        DemoObj.capID=capID;
             //打开视频
          if(DemoObj.iswaiting) return;
          DemoObj.iswaiting = true;
          this.sendMsg(CLT_MSG.BEGIN_CAP, {cap : capID}, function(msg){
            if(msg.err !== 0){
              DemoObj.iswaiting = false;
              return DemoObj.output("打开视频失败");}
            DemoObj.orgwidth = msg.width;
            DemoObj.orgheight = msg.height;
            DemoObj.ResetBox();
            DemoObj.output("打开视频" + capID + "成功，width = " + msg.width + ",height =  " + msg.height);
            DemoObj.iswaiting = false;
          });
      },sendMsg:function (proto, msg, cb) {//向后台发送消息的处理函数
          if(!DemoObj.ws){
            return;
          }

          if(typeof msg !== 'object'){
            if(typeof msg === 'function')
            {
              cb = msg;
              msg = {};
            }
            else{
              msg = {}
            }
          }

          msg.proto = proto;
          if(typeof cb === 'function'){
            DemoObj.context=DemoObj.context+1;
            DemoObj.callback[DemoObj.context] = cb;
            msg.user_data = DemoObj.context;
          }

          DemoObj.ws.send(JSON.stringify(msg));
        },CloseVideo:function() {
        if(DemoObj.iswaiting) return;
        DemoObj.iswaiting = true;
        DemoObj.sendMsg(CLT_MSG.STOP_CAP, function(msg){
          if(msg.err !== 0){
            DemoObj.iswaiting = false;
            return DemoObj.output("关闭视频失败");}
          var cam = document.getElementById('cam');
          DemoObj.orgdrawwidth = 0;
          DemoObj.orgdrawheight = 0
          cam.height = cam.height;
          DemoObj.output("关闭视频成功");
          DemoObj.iswaiting = false;
        });
      },bb:function () {
          //sendMsg(CLT_MSG.SET_COLOR_MODEL,{color:1});// 0\ 1\ 2   //设置颜色模式 只针对截图
          if(DemoObj.iswaiting) return;
          DemoObj.iswaiting = true;

          DemoObj.sendMsg(CLT_MSG.SET_QUALITY, {quality:50},function(msg){ //设置jpg质量
            if(msg.err !== 0) {
              DemoObj.iswaiting = false;
              return;
            }
            DemoObj.output("设置截图图片质量 : quality=" + 50);

            DemoObj.sendMsg(CLT_MSG.GET_PICTURE,{path:"D:\\tp\\1234.jpg",turn:0}, function(msg){   //截图
              if(msg.err !== 0){
                DemoObj.iswaiting = false;
                return;}
              var s = "data:image/jpg;base64," + msg.base64str;
              var s1 =  msg.base64str;
              document.getElementById("Base64IMG").src= s;//网页预览图片
              if(DemoObj.capID==1){
                DemoObj.base64_type1=s1;
              }else if(DemoObj.capID==2){
                DemoObj.base64_type2=s1;
              }else{

              }
              DemoObj.output("base64 长度 : " + s.length);
              DemoObj.iswaiting = false;
              //document.getElementById("Base64IMG").src= "D:\\1234.jpg?" + Math.random();//网页预览图片
            });
          });
        },bbase64:function () {
          //内存截图
          if(DemoObj.iswaiting) return;
        DemoObj.iswaiting = true;

        DemoObj.sendMsg(CLT_MSG.SET_QUALITY, {quality:50},function(msg){ //设置jpg质量
            if(msg.err !== 0) {
              DemoObj.iswaiting = false;
              return;
            }
            DemoObj.output("设置截图图片质量 : quality=" + 50);

            DemoObj.sendMsg(CLT_MSG.GET_PICTURE_MEM,{turn:0}, function(msg){
              if(msg.err !== 0){
                DemoObj.iswaiting = false;
                return;
              }
              var s = "data:image/jpg;base64," + msg.base64str;
              var s2 =   msg.base64str;
              if(DemoObj.capID==1){
                 DemoObj.base64_type1=s2;
              }else if(DemoObj.capID==2){
                 DemoObj.base64_type2=s2;
              }else{

              }
              document.getElementById("Base64IMG").src= s;//网页预览图片
              // alert(s)
              DemoObj.output("base64 长度 : " + s.length);
              DemoObj.iswaiting = false;
            });
          });

      },getBase64String:function (v) {
            if(DemoObj.capID==1){
               return DemoObj.base64_type1;
            }else if(DemoObj.capID==2){
              return DemoObj.base64_type2;
            }else{
               return "";
            }
      }
   }
  }



}();
export default gaopaiyi;
